package com.suxin.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Tang
 * @classname NioClient
 * @description [  ]
 * @date 2021/7/3 13:59
 */
public class NioClient {

    public static void main(String[] args) throws Exception{

        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
        socketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);

        ByteBuffer allocate = ByteBuffer.allocate(1024);

        System.out.println("服客户端启动监听...");
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()) {
                    SelectableChannel selectableChannel = selectionKey.channel();
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    if (selectionKey.isReadable()) {
                        allocate.clear();
                        allocate.rewind();
                        channel.read(allocate);
                        allocate.flip();
                        String msg = new String(allocate.array());
                        System.out.println("客户端收到数据为: " + msg);
                    }
                }
            }
            iterator.remove();
        }
    }
}